#pragma once
#include <iostream>
#include<list>
#include<string>
#include <memory>
#include <algorithm>
#include <sys/types.h>
#include <sys/socket.h>
#include "InetAddr.hpp"
#include"Log.hpp"
#include"Mutex.hpp"

using namespace LogModule;
using namespace LockModule;

class UserInterface
{
public:
    virtual ~UserInterface() = default;
    virtual void Sendto(int sockfd, const std::string &message) = 0;
    virtual bool operator==(const InetAddr &u) = 0;
    virtual std::string Id() = 0;
};

class User : public UserInterface
{
public:
    User(const InetAddr &id):_id(id)
    {
    }
    void Sendto(int sockfd, const std::string &message) override
    {
        LOG(LogLevel::DEBUG)<<"send message to"<<_id.Addr()<<"info"<<message;
        int n = ::sendto(sockfd, message.c_str(), message.size(), 0, _id.NetAddr(), _id.NetAddrLen());
    }
    bool operator==(const InetAddr &u) override
    {
        return _id==u;
    }
    std::string Id() override
    {
        return _id.Addr();
    }
    ~User()
    {
    }

private:
    InetAddr _id;
};


//对路由进行管理(用户)
class UserManager
{
    public:
    UserManager()
    {

    }
    void AddUser(InetAddr &id)
    {
        //先看list里面是否已经存在该用户
        LockGuard lockguard(_lock);
        for(auto &user:_onlince_user)
        {
            if(*user==id)
            {
                LOG(LogLevel::INFO)<<"用户已经存在: "<<id.Addr();
                return;
            }
        }

        //不存在用户,要创建用户
        _onlince_user.push_back(std::make_shared<User>(id));
        LOG(LogLevel::INFO)<<"用户创建成功："<<id.Addr();
    }
    void DelUser(InetAddr &id)
    {
        auto pos=std::remove_if(_onlince_user.begin(),_onlince_user.end(),[&id](std::shared_ptr<UserInterface> &user){
            return *user==id;
        });
        _onlince_user.erase(pos,_onlince_user.end());
        PrintUser();
    }
    void Router(int sockfd,const std::string &message)
    {
        LockGuard lockguard(_lock);
        for(auto &user:_onlince_user)
        {
            user->Sendto(sockfd,message);
        }
    }
    void PrintUser()
    {
         for(auto user:_onlince_user)
        {
             LOG(LogLevel::DEBUG)<<"在线用户："<<user->Id();
        }
       
    }
    ~UserManager()
    {

    }
    private:
    std::list<std::shared_ptr<UserInterface>> _onlince_user;
    Mutex _lock;

};